package m.fun.service;

import m.base.util.PowerUtil;
import m.common.model.util.ModelCheckUtil;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.service.Service;
import m.fun.model.AskDetail;
import m.fun.model.AskInfo;
import m.store.model.GoodsOutRecord;
import m.store.model.OrderModel;
import m.store.model.SaleInfo;
import m.store.service.SaleInfoService;
import m.store.service.StoreNumberService;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.ObjectUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AskInfoService extends Service {
    public void submit(AskInfo model, List<AskDetail> details) throws MException, SQLException {
        if(null==details||details.isEmpty()) throw new MException(this.getClass(),"请选择需求商品");
        ModelCheckUtil.checkNotNull(model,"name","dutyUser","tel");
        model.setSubmitDate(new Date());
        if(ObjectUtil.isEmptyOid(model)){
            model.setOid(GenerateID.generatePrimaryKey());
            model.setBuildStatus(AskInfo.Build_No);
            ModelUpdateUtil.insertModel(model);
        }else{
            ModelUpdateUtil.updateModel(model,"type","name","dutyUser","tel","address","description","submitDate");
        }
        ModelUpdateUtil.delete(AskDetail.class, QueryCondition.eq("ask.oid",model.getOid()));
        details.forEach(item->{
            item.setOid(GenerateID.generatePrimaryKey());
            item.setAsk(model);
        });
        ModelUpdateUtil.insertModels(details.toArray(new AskDetail[0]));
    }
    public void buildSaleInfo(String oid) throws Exception {
        AskInfo model= ModelQueryList.getModel(AskInfo.class,oid,"*");
        if(null==model) throw new MException(this.getClass(),"询价信息不存在");
        if(AskInfo.Build_Done.equals(model.getBuildStatus())) throw new MException(this.getClass(),"已生成，不能重复生成。");
        if(ObjectUtil.isEmptyOid(model.getGuest())) throw new MException(this.getClass(),"请先保存关联客户");
        PowerUtil.verifyUserData(model.getUser().getOid());
        TransactionManager tm=new TransactionManager();
        try {
            tm.begin();
            //生成调拨出库
            if(ObjectUtil.isEmptyOid(model.getSale())) {
                List<AskDetail> recordList=ModelQueryList.getModelList(AskDetail.class,
                    new String[]{"*","record.*","goods.*"}, null,
                    QueryCondition.and(
                        QueryCondition.eq("ask.oid", model.getOid()),
                        QueryCondition.notEmpty("record.oid")
                    )
                );
                if(recordList.isEmpty()) throw new MException(this.getClass(),"至少设置一个库存信息才能生成出库");
                SaleInfo sale = new SaleInfo();
                sale.setOrderNo(StoreNumberService.getNextSaleNumber());
                sale.setStore(PowerUtil.getSessionStore(true));
                sale.setStatus(OrderModel.Status_Register);
                sale.setType(SaleInfo.Type_Sale);
                sale.setInputDate(new Date());
                sale.setInputUser(model.getUser());
                sale.setSaleDate(sale.getInputDate());
                sale.setGuest(model.getGuest());
                sale.setRemark("询价生成订单");
                List<GoodsOutRecord> saleRecords = new ArrayList<>();
                for(AskDetail item : recordList){
                    GoodsOutRecord record = new GoodsOutRecord();
                    record.setRecord(item.getRecord());
                    record.setNum(item.getNum());
                    record.setPrice(item.getGoods().getOfferPrice());
                    if(null==record.getPrice()) record.setPrice(0d);
                    record.setPreferential(0d);
                    record.setRemark("");
                    saleRecords.add(record);
                }
                getService(SaleInfoService.class).save(sale,saleRecords);
                model.setSale(sale);
                model.setBuildStatus(AskInfo.Build_Done);
                ModelUpdateUtil.updateModel(model, "sale.oid","buildStatus");
            }
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw new MException(this.getClass(),"生成出库失败:"+e.getMessage());
        }
    }
}
